/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-undef */
const fs = require('fs').promises;
const path = require('path');
const iconv = require('iconv-lite');
const xmlTool = require('fast-xml-parser');

function getFileEncoding(buffer) {
  try {
    const text = buffer.toString('utf-8');
    const parser = new xmlTool.XMLParser({ ignoreAttributes: false });
    const json = parser.parse(text);
    return json['?xml']['@_encoding'];
  } catch (e) {
    console.log(e);
  }
}

function decode(buffer, encoding) {
  try {
    const result = iconv.decode(buffer, encoding);
    return result;
  } catch (e) {
    return;
  }
}

async function convert(buffer, outputPath) {
  try {
    buffer = decode(buffer, 'gbk');
    const convertedData = iconv.encode(buffer, 'utf8');
    const text = convertedData.toString('utf-8');
    const parser = new xmlTool.XMLParser({ ignoreAttributes: false });
    const json = parser.parse(text);
    json['?xml']['@_encoding'] = 'UTF-8';
    const builder = new xmlTool.XMLBuilder({
      ignoreAttributes: false,
      suppressBooleanAttributes: false,
      format: true
    });
    await fs.writeFile(outputPath, builder.build(json), 'utf-8');
    console.log(`++++++ converted ${outputPath}`);
  } catch (e) {
    console.log(`Error: ------ failed converting ${outputPath}: ${e}`);
  }
}

async function handleDir(dir) {
  try {
    const files = await fs.readdir(dir);
    for (const file of files) {
      const filePath = path.join(dir, file);
      const stats = await fs.stat(filePath);
      if (stats.isDirectory()) {
        await handleDir(filePath);
      } else {
        await handleFile(filePath);
      }
    }
  } catch (e) {
    console.log(`Error: ------ failed read folder ${dir}`);
  }
}

async function handleFile(filePath) {
  const fileExt = path.extname(filePath);
  if (!ext.includes(fileExt)) {
    return;
  }
  const filename = path.basename(filePath);
  if (['GEN_', 'CHECK_'].some(prefix => filename.startsWith(prefix))) {
    return;
  }
  let buffer;
  try {
    buffer = await fs.readFile(filePath);
  } catch (e) {
    console.log('Error: ------ failed to read file ', filePath, e);
    return;
  }

  const encoding = getFileEncoding(buffer);
  if (!encoding) {
    console.log(`warning: ------ ${filePath} no encoding attrbute`);
    return;
  }
  if (encoding.toLowerCase() === 'utf-8' || encoding.toLowerCase() === 'utf8') {
    return;
  }

  convert(buffer, filePath);
}


const rootDirs = [
  // 'F:\\zgling\\ACoreIDEPro\\target'
  'F:\\zgling\\ACoreIDEPro\\template'
];
const ext = ['.xsd', '.cfg', '.xml', '.mtp'];


rootDirs.forEach((dir) => {
  handleDir(dir);
});

// handleFile(
//   // 'F:\\zgling\\ACoreVIDE\\target\\acoreos653mp\\config\\arinc\\coreos\\coreOs.xsd'
//   'F:\\ACoreOSMP_IDE_win32\\back\\target\\acoreos2x\\msl\\board\\ppc\\ppc7447_mmp\\mtp\\rom_burn.mtp'
// );
